<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加区域 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 数据展示区域 -->
      <el-table :data="rolesList" border style="widht: 100%" stripe :expand-row-keys="expandKeys" row-key="id">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template #default="scope">
            <el-row
              v-for="(item1, i1) of scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级菜单 -->
              <el-col :span="5">
                <el-tag closable  @close="removerRightById(scope.row,item1.id)">{{ item1.authName }}</el-tag>
              </el-col>
              <!-- 渲染二级和三级菜单 -->
              <el-col :span="19">
                <!-- 通过for循环渲染二级权限 -->
                <el-row
                  v-for="(item2, i2) of item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable  @close="removerRightById(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, i3) of item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removerRightById(scope.row,item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列表 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称">
          <template #default="scope">
            {{ scope.row.roleName }}
          </template>
        </el-table-column>
        <el-table-column label="角色描述">
          <template #default="scope">
            {{ scope.row.roleDesc }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small">编辑</el-button>
            <el-button type="danger" size="small">删除</el-button>
            <el-button type="warning" size="small" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
     <el-dialog v-model="setRightDialogVisible" title="用户权限分配" width="50%" center @close="closeSetRIghtDialogClosed">
      <div class="el-dialog-div">
        <!-- 树形控件 -->
        <el-tree 
          :data="rightsList" 
          :props="treeProps"   
          node-key="id" 
          show-checkbox 
          :default-expand-all="true"
          :default-checked-keys="defKeys"
          ref="treeRef"
        />
      </div>
      
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeSetRIghtDialogClosed">取消</el-button>
          <el-button type="primary" @click="allotRights">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import axios from '../../http/axios.js'

export default {
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      expandKeys: [],
      setRightDialogVisible: false, // 显示分配权限对话框
      rightsList: [], // 权限列表数据
      treeProps: { // 树形控件绑定对象
        label : 'authName',
        children : 'children'
      },
      defKeys: [], // 默认展示权限视图的角色id数组
      roleId: '', // 即将分配权限的用户id
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() { // 获取用户信息
      const { data: res } = await axios.get('/roles')

      if (res.meta.status !== 200) {
        this.$message({
          type: 'error',
          message: '获角色列表数据失败',
        })
      } else {
        this.rolesList = res.data
      }
    },
    removerRightById(role, rightId) {  // 删除用户权限
      this.$messageBox
        .confirm('该操作会删除用户权限', '删除权限', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(async () => {

          const { data: res} = await axios.delete(`roles/${role.id}/rights/${rightId}`);

          if(res.meta.status !== 200){
            this.$message({
              type: 'error',
              message: '删除角色权限失败'
            });
          }else{
            this.$message({
              type: 'success',
              message: '删除角色权限成功'
            });
            this.expandKeys= [role.id];
            role.children = res.data;
            
          }
        })
        .catch(() => {
          console.log('取消删除');
        })
    },
    closeSetRIghtDialogClosed(){ // 关闭权限分配对话框
      this.setRightDialogVisible = false;
      this.defKeys = [];
    },
    async showSetRightDialog(role){  // 展示分配权限对话框
      this.roleId = role.id;

      const { data: res } = await axios.get('rights/tree');

      if(res.meta.status !== 200){
        this.$message({
          type: 'error',
          message: '获取权限列表失败'
        })
      }else{
        this.rightsList = res.data;
        this.getLeafKeys(role,this.defKeys);
      };

      this.setRightDialogVisible = true;
    },
    getLeafKeys(node,arr){ // 递归绑定权限数组
      if(!node.children){
        return arr.push(node.id);
      }

      node.children.forEach(item => {
        this.getLeafKeys(item,arr);
      });
    },
    async allotRights(){ // 点击为角色分配权限
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];

      const idStr = key.join(',');

      const { data: res} = await axios.post(`roles/${this.roleId}/rights`,{ rids: idStr});

      if(res.meta.status !== 200){
        this.$message({
          type: 'error',
          message: '设置用户权限失败'
        })
      }else{
        this.$message({
          type: 'success',
          message: '用户权限分配成功'
        })
        this.getRolesList();
        this.setRightDialogVisible = false;
      };

    }
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

.el-dialog-div {
  height: 50vh;
  overflow-x: hidden;
}
</style>